const {sign} = require("jsonwebtoken");
const axios = require("axios");
/**
 * 生成 JWT Token
 * @returns
 */
 const generateJWT=()=> {
    console.log('JWT')
    let  fingerprint = "eG1hIqcOQhaogUMq16B81PW4r5YQD2LBsOYM6XIZvIQ";
    let privateKey = "-----BEGIN PRIVATE KEY-----\n" +
        "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQD4+mNUktNmetxk\n" +
        "ARVj2XIBDVVVZLqP5rV4+FCiYX/yBgLmzGf3TajxlwI9JxJNovNQUwGXm/oSCXhw\n" +
        "+m/mjde1mKBY+79e67EsmxAvyBKgaZBoN0gr8UKR5AHKjaAK2JKeQNxsja3M6jXW\n" +
        "iLDKzNMIcMLgoeYuPQXoNE5Da+lCl3ZB3cIuQwJZu1qqkvK7ztQfDQoiWZSw/pVv\n" +
        "LM1DLGs/78VLbMiyO5+eHrEnGVVUZh6W9fNLtON8onwnjuh838MPRRYzbQF2gTLH\n" +
        "Ssk56S39FBWBfEeIVbM64eTc/PbleSdDtijAQOiOyHaZYvRTLADR71lJKwVsok5W\n" +
        "82jqWW1TAgMBAAECggEAWEfDz5mN/pDCs2zU7kYMD8ZwAurH4b0+jEmTobfre1/Z\n" +
        "SIeit4PgSuUt5IwFh+Sm3EzKTD0AgsO74mdSJRAXM6sN8+8zkE8Gz9edeiu5Owqj\n" +
        "KuirHPWbEoqjffQQkrfu6ND7tzvXK8jB1TM7aHUOwLfmyWpuaOe3P/nH5E0PdM33\n" +
        "lG1UAttOUzVofOMGYAzCrVqUzbzo+nDIzGtSR5rQPIH9Psntir+fl+unCupIRk9+\n" +
        "HM2f2B9x2qGGLRgxBir2En+ofOwBUoHqh9sImvHADxeLq0Uiy8HRhYpeONQSjaD6\n" +
        "kN38FKcHLFCykMvcG/9fD2E8i+DFRvTkP5zjFrGSUQKBgQD+YuJNn38NYKnmQ+I4\n" +
        "EMpTDDQgBGChEyxf6ntqp7NlLD9NFsq6TEDAk97N74kL3OrSHOpzXVty0oozg0zY\n" +
        "DyTS5xY4qwMAy/8CwIcxm35sKlQmHykveZ0bcFE7y9cclHhuOaS2zUC6HTewDFhf\n" +
        "DNkIT1i9EBrCgNGtJW9FlJmWgwKBgQD6jrilNfZI2/cOe4zfXR9o8LnQDbncvIsy\n" +
        "zOwj82a84OqfsRpgcW98CF5Wi1u/EZdJlkzSTM2cd0VRCPftGB1CYV+kT7YY/Ddz\n" +
        "NtFsk7A5BRhE+YOa7P9tVaV0/pewfUi0IKmskqzaa9D1xiQ/W3LkE7DySK6CPKuE\n" +
        "ifvs9hWU8QKBgEkh8n9wYB1fcdjCIVIO+augcYfW2lTUZ0h3591Esx1d+CDYcZXX\n" +
        "gDIdEMvRlmuzqkqXh4t9BmJfRt4CXGAtEmATkV7fQzDCdOC8quFHG7RLAwAmqzd7\n" +
        "1f/ibWgsdP5BbNH7fnATWA1pgu34zpsc3XQ3I4LPE3JhiGYnwfKWAwWzAoGBAJyQ\n" +
        "wmC6L4Onr+Gk4opQrmfsxK91ZEbCqli8JHLyjahJA1N2X30UZQ2kTQ7XViU24Mpi\n" +
        "2O4wf+rdvLq+V+4Xu3DXV+RcyvUh5aRhBMxMHToELP4szEfrAFFZy2IoFLF8GAo2\n" +
        "vs/Pd6Ok65Yokk3k3w4WH+PF9wX601Kmxn1z6FiBAoGAfImszXaiWmZV1l3oul/w\n" +
        "tcCCoH+gVuYavyqJ6X50vMLGyNzU4BPvBMblIU1Ho/uH1OmokP4D1iZA94kcXd6H\n" +
        "7ek35BHJiCIfv5U+6SWc7jsWvVVgS7VcaTbDtc0K7/szbzXStLnfCQo/hdMuu925\n" +
        "7Wzr8IAZTLsuoHJjIsJWkrM=\n" +
        "-----END PRIVATE KEY-----";

    const payload = {
        iss: '1115476792395', // coze appid
        exp: Math.floor(Date.now() / 1000) + 60, // 1分钟后过期
        iat: Math.floor(Date.now() / 1000),
        aud:'api.coze.cn',
        jti: Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15),

    };

    const options = {
        algorithm: 'RS256',
        header: {
            alg: 'RS256',
            typ: 'JWT',
            kid: fingerprint // 公钥指纹
        }
    };

    return sign(payload, privateKey, options);
}

module.exports = {
    chat: async ({bot_id, content, access_token,user_id,conversation_id})=>{
        // https://api.coze.cn/v3/chat
        const result = await axios.post('https://api.coze.cn/v3/chat?conversation_id='+conversation_id, {
            bot_id,
            user_id:user_id.toString(),
            additional_messages:[{
                role:'user',
                content:content,
                content_type:'text',
            }],
            stream:false,
            auto_save_history:true,
        }, {
            headers: {
                'Authorization': `Bearer ${access_token}`,
                'Content-Type': 'application/json'
            },
            timeout: 10000,
        });
        return result.data;
    },


    /**
     * 获取机器人信息
     * @param bot_id
     * @param access_token
     * @returns {Promise<any>}
     */
     getBotInfo:async (bot_id,access_token)=>{
         const result = await axios.get('https://api.coze.cn/v1/bot/get_online_info', {
             headers: {
                 'Authorization': `Bearer ${access_token}`,
                 'Content-Type': 'application/json'
             },
             params: {
                 bot_id: bot_id
             },
         });
         return result.data;
     },

    getCachedAccessToken: async () => {

        const assertion = generateJWT();
        console.log('JWT:',assertion)
        const result = await axios.post('https://api.coze.cn/api/permission/oauth2/token', {
            grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
            duration_seconds:86399,
        }, {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': `Bearer ${assertion}`,
            },
            timeout: 10000,
        });

        console.log(result.data);

        if (result.status === 200 && result.data && result.data.access_token) {
            const { access_token, expires_in } = result.data;
            const expired_at = new Date(Date.now() + (expires_in || 7200) * 1000);

            // 更新或插入token信息
            const row = {
                access_token,
                expired_at
            };
            // 插入或更新数据库
            return row.access_token;
        } else {
            return null;
        }
    }

}